package com.lechi.web.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.lechi.iot.android.entity.OutDeviceCmd;
import com.lechi.web.common.annotation.Log;
import com.lechi.web.common.core.controller.BaseController;
import com.lechi.web.common.core.domain.AjaxResult;
import com.lechi.web.common.core.domain.entity.SysUser;
import com.lechi.web.common.core.domain.model.LoginUser;
import com.lechi.web.common.core.page.TableDataInfo;
import com.lechi.web.common.enums.BusinessType;
import com.lechi.web.common.enums.ErrorCodeEnum;
import com.lechi.web.common.exception.ExceptionUtil;
import com.lechi.web.common.exception.ServiceException;
import com.lechi.web.common.utils.SecurityUtils;
import com.lechi.web.constants.AppCmdConstants;
import com.lechi.web.service.IIotDeviceService;
import com.lechi.web.service.IIotPublishAppService;
import com.lechi.web.service.IIotUpgradeLogService;
import com.lechi.web.system.domain.IotPublishApp;
import com.lechi.web.system.domain.IotUpgradeLog;
import com.lechi.web.vo.IotContentPublishVo;
import com.lechi.web.vo.IotPublishAppAddVo;
import com.lechi.web.vo.IotPublishAppApproveVo;
import com.lechi.web.vo.IotPublishAppUpdateVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.lechi.web.constants.AppCmdConstants.RESOURCE_UPDATE;
import static com.lechi.web.constants.AppCmdConstants.UN_PUBLISH;

/**
 * 内容发布管理Controller
 *
 * @author yangguang
 * @date 2024 -07-10
 */
@Slf4j
@RestController
@RequestMapping("/iot/app")
@RequiredArgsConstructor
public class IotPublishAppController extends BaseController {

    private final IIotPublishAppService iotPublishAppService;


    private final IIotUpgradeLogService iotUpgradeLogService;


    private final IIotDeviceService androidDeviceService;


    /**
     * 查询内容发布管理列表
     *
     * @param iotPublishApp the iot publish app
     * @return the table data info
     */
    @GetMapping("/list")
    //    @PreAuthorize("@ss.hasPermi('iot:program:query')")
    public TableDataInfo list(IotPublishApp iotPublishApp) {
        startPage();
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();
        if (!user.isAdmin()) {
            iotPublishApp.setCreateBy(user.getUserName());
        }
        List<IotPublishApp> list = iotPublishAppService.selectIotPublishAppList(iotPublishApp);
        return getDataTable(list);
    }

    /**
     * 获取内容发布管理详细信息
     *
     * @param id the id
     * @return the info
     */
    @GetMapping(value = "/{id}")
    //    @PreAuthorize("@ss.hasPermi('iot:program:query')")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        final IotPublishApp iotPublishApp = iotPublishAppService.selectIotPublishAppById(id);
        return AjaxResult.success(iotPublishApp);
    }

    /**
     * 新增内容发布管理
     *
     * @param iotPublishAppAddVo the iot publish app add vo
     * @return the ajax result
     */
    @PostMapping("/add")
    //    @PreAuthorize("@ss.hasPermi('iot:program:add')")
    public AjaxResult add(@RequestBody IotPublishAppAddVo iotPublishAppAddVo) {
        IotPublishApp iotPublishApp = new IotPublishApp();
        BeanUtils.copyProperties(iotPublishAppAddVo, iotPublishApp);
        iotPublishApp.setCreateBy(SecurityUtils.getUsername());
        return toAjax(iotPublishAppService.insertIotPublishApp(iotPublishApp));
    }

    /**
     * 复制发布内容 default 详细信息
     *
     * @param id the id
     * @return the ajax result
     */
    @GetMapping(value = "/copy/{id}")
    @Transactional(rollbackFor = Exception.class)
    //    @PreAuthorize("@ss.hasPermi('iot:program:edit')")
    public AjaxResult clone(@PathVariable("id") Long id) {
        IotPublishApp iotPublishApp = Optional.ofNullable(iotPublishAppService.selectIotPublishAppById(id)).orElseThrow(ExceptionUtil.notExitsErrorException);
        iotPublishApp.setStatus(UN_PUBLISH);
        iotPublishAppService.insertIotPublishApp(iotPublishApp);

        return success();
    }

    /**
     * 新增内容发布管理
     *
     * @param iotContentPublishVo the iot content publish vo
     * @return the ajax result
     */
    @PostMapping("/publish")
    //    @PreAuthorize("@ss.hasPermi('iot:program:edit')")
    public AjaxResult add(@RequestBody IotContentPublishVo iotContentPublishVo) {
        final IotPublishApp iotPublishApp = iotPublishAppService.selectIotPublishAppById(iotContentPublishVo.getId());
        if (Objects.equals(iotPublishApp.getStatus(), UN_PUBLISH)) {
            throw new ServiceException(ErrorCodeEnum.UNAPPROVED_ERROR.getValue(), ErrorCodeEnum.UNAPPROVED_ERROR.getKey());
        }

        final JSONArray jsonArray = JSONUtil.parseArray(iotPublishApp.getElementList());
        final List<OutDeviceCmd.DownLoadTask> downLoadTasks = JSONUtil.toList(jsonArray, OutDeviceCmd.DownLoadTask.class);

        //** 待删除
//        List<File> fileNameList = new ArrayList<>();
//        String zipFileName = StringUtils.format("image_{}.{}", Seq.getId(Seq.uploadSeqType), "zip");
//        List<OutDeviceCmd.DownLoadTask> newDownLoadTasks = new ArrayList<>();
//        for (OutDeviceCmd.DownLoadTask downLoadTask : downLoadTasks) {
//            if ("image".equals(downLoadTask.getFileType())) {
//                final String filePath = uploadPath + downLoadTask.getDownLoadUrl().substring(downLoadTask.getDownLoadUrl().lastIndexOf("/app/") + 4);
//                fileNameList.add(new File(filePath));
//                continue;
//            }
//            newDownLoadTasks.add(downLoadTask);
//        }
//        File zipFile = new File(uploadPath + File.separator + zipFileName);
//        ZipUtil.zip(zipFile, false, fileNameList.toArray(new File[fileNameList.size()]));
//        OutDeviceCmd.DownLoadTask downLoadTask = new OutDeviceCmd.DownLoadTask();
//        downLoadTask.setFileType("image");
//        downLoadTask.setDownLoadUrl(leChiConfig.getNginxip() + "/profile/app/" + zipFileName);
//        downLoadTask.setFileName(zipFileName);
//        downLoadTask.setMd5(DigestUtil.md5Hex(zipFile));
//        newDownLoadTasks.add(downLoadTask);
        //** 待删除

        final List<String> deviceSNList = iotContentPublishVo.getDeviceSN();
        deviceSNList.forEach(deviceSN -> {
            IotUpgradeLog iotUpgradeLog = new IotUpgradeLog();
            iotUpgradeLog.setDeviceSN(deviceSN);
            iotUpgradeLog.setStatus(AppCmdConstants.BEGIN);
            iotUpgradeLog.setLogType(RESOURCE_UPDATE);
            iotUpgradeLog.setFileId(iotContentPublishVo.getId());
            iotUpgradeLog.setCreateBy(SecurityUtils.getUsername());
            iotUpgradeLog.setParam(iotPublishApp.getElementList());
            iotUpgradeLogService.insertIotUpgradeLog(iotUpgradeLog);
            OutDeviceCmd outDeviceCmd = new OutDeviceCmd();
            outDeviceCmd.setPublishContent(iotPublishApp.getPublishContent());
            outDeviceCmd.setCmd(RESOURCE_UPDATE);
            outDeviceCmd.setUpdateLogId(iotUpgradeLog.getId());
            outDeviceCmd.setDeviceSN(deviceSN);
            outDeviceCmd.setDownLoadTask(downLoadTasks);
            androidDeviceService.sendCmdToApp(deviceSN, outDeviceCmd);// 下载视频
        });

        iotPublishApp.setId(iotContentPublishVo.getId());
        iotPublishApp.setStatus(AppCmdConstants.PUBLISHED);
        iotPublishAppService.updateIotPublishApp(iotPublishApp);
        return AjaxResult.success();
    }

    /**
     * 修改内容发布管理
     *
     * @param iotPublishAppApproveVo the iot publish app approve vo
     * @return the ajax result
     */
    @PostMapping("/approve")
    //    @PreAuthorize("@ss.hasPermi('iot:program:edit')")
    public AjaxResult approve(@RequestBody IotPublishAppApproveVo iotPublishAppApproveVo) {
        IotPublishApp iotPublishApp = new IotPublishApp();
        iotPublishApp.setId(iotPublishAppApproveVo.getId());
        iotPublishApp.setStatus(AppCmdConstants.APPROVED);
        iotPublishAppService.updateIotPublishApp(iotPublishApp);
        return AjaxResult.success();
    }

    /**
     * 修改内容发布管理
     *
     * @param iotPublishAppUpdateVo the iot publish app update vo
     * @return the ajax result
     */
    @Log(title = "内容发布管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    //    @PreAuthorize("@ss.hasPermi('iot:program:edit')")
    public AjaxResult edit(@RequestBody IotPublishAppUpdateVo iotPublishAppUpdateVo) {
        IotPublishApp iotPublishApp = new IotPublishApp();
        BeanUtils.copyProperties(iotPublishAppUpdateVo, iotPublishApp);
        iotPublishAppService.updateIotPublishApp(iotPublishApp);
        return AjaxResult.success();
    }

    /**
     * 删除内容发布管理
     *
     * @param ids the ids
     * @return the ajax result
     */
    @Log(title = "内容发布管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    //    @PreAuthorize("@ss.hasPermi('iot:program:remove')")
    public AjaxResult remove(@PathVariable Long[] ids) {
        iotPublishAppService.deleteIotPublishAppByIds(ids);
        return AjaxResult.success();
    }
}
